/**
 * mDNS 服务发现管理类
 * 负责处理设备扫描、发现和离线等功能
 */
class MDNSManager {
  constructor() {
    // 扫描状态
    this.isScanning = false;
    // 事件回调
    this.onDeviceFoundCallback = null;
    this.onDeviceLostCallback = null;
    this.onErrorCallback = null;
    // 调试模式
    this.debug = true;
    // 服务类型
    this.serviceType = '_iotctrl-udp._udp.';
    // 设备名称
    this.deviceName = 'Smart Socket';
    // 新增：设备名称匹配模式
    this.deviceNamePattern = /^Smart Socket-[0-9a-fA-F]{6}$/;
  }

  /**
   * 开始扫描设备
   * @returns {Promise} 扫描结果
   */
  startScan() {
    this.log('准备开始扫描');
    
    if (this.isScanning) {
      this.warn('扫描已在进行中');
      return Promise.reject(new Error('扫描已在进行中'));
    }

    return new Promise((resolve, reject) => {
      wx.startLocalServiceDiscovery({
        serviceType: this.serviceType,
        success: () => {
          this.isScanning = true;
          this.log('扫描启动成功');
          this.setupListeners();
          resolve();
        },
        fail: (err) => {
          this.error('扫描启动失败:', err);
          reject(err);
        }
      });
    });
  }

  /**
   * 停止扫描
   * @returns {Promise} 停止结果
   */
  stopScan() {
    this.log('准备停止扫描');
    
    if (!this.isScanning) {
      this.log('扫描未在进行');
      return Promise.resolve();
    }

    return new Promise((resolve) => {
      wx.stopLocalServiceDiscovery({
        complete: () => {
          this.isScanning = false;
          this.log('扫描已停止');
          this.removeListeners();
          resolve();
        }
      });
    });
  }

  /**
   * 设置事件监听器
   * @private
   */
  setupListeners() {
    // 监听设备发现事件
    wx.onLocalServiceFound(this.handleDeviceFound.bind(this));
    // 监听设备离线事件
    wx.onLocalServiceLost(this.handleDeviceLost.bind(this));
    // 监听扫描错误事件
    wx.onLocalServiceResolveFail(this.handleError.bind(this));
  }

  /**
   * 移除事件监听器
   * @private
   */
  removeListeners() {
    wx.offLocalServiceFound();
    wx.offLocalServiceLost();
    wx.offLocalServiceResolveFail();
  }

  /**
   * 处理设备发现
   * @private
   */
  handleDeviceFound(result) {
    const { serviceName, serviceType, ip, port } = result;
    this.log('发现服务:', result);

    // 判断是否为目标设备：检查服务类型和设备名称格式
    if (serviceType !== this.serviceType || !this.deviceNamePattern.test(serviceName)) {
      this.log('不是目标设备，跳过:', serviceType, serviceName);
      return;
    }

    // 构造设备信息
    const device = {
      id: serviceName,
      name: serviceName,
      hostname: serviceName,
      type: serviceType,
      ip: ip,
      port: port,
      connected: false
    };

    this.log('发现智能插座设备:', device);
    this.onDeviceFoundCallback && this.onDeviceFoundCallback(device);
  }

  /**
   * 处理设备离线
   * @private
   */
  handleDeviceLost(result) {
    const { serviceName } = result;
    this.log('服务离线:', result);
    this.onDeviceLostCallback && this.onDeviceLostCallback(serviceName);
  }

  /**
   * 处理错误
   * @private
   */
  handleError(error) {
    this.error('服务解析失败:', error);
    this.onErrorCallback && this.onErrorCallback(error);
  }

  /**
   * 日志方法
   * @private
   */
  log(...args) {
    if (this.debug) console.log('[mDNS]', ...args);
  }

  warn(...args) {
    if (this.debug) console.warn('[mDNS]', ...args);
  }

  error(...args) {
    if (this.debug) console.error('[mDNS]', ...args);
  }

  /**
   * 设置设备发现回调
   */
  onDeviceFound(callback) {
    this.onDeviceFoundCallback = callback;
  }

  /**
   * 设置设备离线回调
   */
  onDeviceLost(callback) {
    this.onDeviceLostCallback = callback;
  }

  /**
   * 设置错误回调
   */
  onError(callback) {
    this.onErrorCallback = callback;
  }
}

export default MDNSManager; 